import moment from 'moment';
import React from 'react';
import nzh from 'nzh/cn';
import { parse, stringify } from 'qs';

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}
export function getQueryVariable(variable) {//获取查询参数 url内
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}
export function checkList(list){
  if(list){
    if(list.length==0){
      message.warning(
        '没有查询到列表数据!'
      );
    }
  }else{
    console.log("检查列表大小失败list为undefined！")
  }
}
//制造级联数据   参数分别为 {lable 名称 value 名称 children 名称},数据集
//注意事项 ： 此函数必须每级的数据key名称一致
export function markCascadeList({lable_name,value_name,children_name},source) {
  const getThreeList = (mark_list)=>{
    const return_list = [];
    mark_list.map((item)=>{
      return_list.push({
        value: item[value_name],
        label: item[lable_name],
        children:item[children_name] && item[children_name].length>0 ? getThreeList(item[children_name]) :undefined
      })
    })
    return return_list;
  }
  try {
    if (source && source.length>0){
      return getThreeList(source);
    }else {
      console.error("utle.js markCascadeList() err !使用此函数数据源必须为数组类型");
    }
  }catch (e){
    console.log(e);
  }

}
export function queryUserInfo() { //用户信息

  let userInfo = []

  const info = JSON.parse(window.sessionStorage.getItem("userInfo"))
  if (info) {
    userInfo = info
  }

  return userInfo
}
export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  return nzh.toMoney(n);
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  }
  if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

export function formatWan(val) {
  const v = val * 1;
  if (!v) return '';

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
        <span
          style={{
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            marginLeft: 2,
          }}
        >
          万
        </span>
      </span>
    );
  }
  return result;
}

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export function isAntdPro() {
  return window.location.hostname === 'preview.pro.ant.design';
}

export const importCDN = (url, name) =>
  new Promise(resolve => {
    const dom = document.createElement('script');
    dom.src = url;
    dom.type = 'text/javascript';
    dom.onload = () => {
      resolve(window[name]);
    };
    document.head.appendChild(dom);
  });
export const getAMap = (isLoaded) => {
  return new Promise(function (resolve, reject) {
    if (isLoaded) {
      resolve()
    } else {
      let script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src = 'http://webapi.amap.com/maps?v=1.3&key=d430ca41a38f56c6305e899b2263c747&callback=init'
      // script.onload = resolve
      script.onerror = reject
      script.onload = function () {
        //isLoaded = true
        resolve(window.AMap)
      }
      document.head.appendChild(script)
    }
  })
}
export function getNewRoutes(role_permissions){
  const routes = [
    { //定义首页跳转到哪
      path: '/',
      exact:true,
    }
  ]

  if(role_permissions && role_permissions.length>0){
    role_permissions.map((item)=>{
      if(!item.permission_pid){
        routes.push({
          permission_id:item.permission_id,
          icon:item.icon && item.icon!=''?item.icon:undefined,
          hideInMenu:!item.left_menu,
          is_left_menu:item.is_left_menu,
          path:"/"+item.route,
          name:item.permission_name,
          authority:item.roles,

        })
      }
    })
    routes.map(item=>{
      for(let i = 0 ; i<role_permissions.length;i++){
        if(role_permissions[i].permission_pid && role_permissions[i].permission_pid === item.permission_id){
          if(item.routes){
            item.routes.push({
              permission_id:role_permissions[i].permission_id,
              icon:role_permissions[i].icon && role_permissions[i].icon!=''?role_permissions[i].icon:undefined,
              hideInMenu:!role_permissions[i].left_menu,
              is_left_menu:item.is_left_menu,
              path:item.path+"/"+role_permissions[i].route,
              name:role_permissions[i].permission_name,
              authority:role_permissions[i].roles,
            })
          }else {
            item.routes = [
              {
                permission_id:role_permissions[i].permission_id,
                icon:role_permissions[i].icon && role_permissions[i].icon!=''?role_permissions[i].icon:undefined,
                hideInMenu:!role_permissions[i].left_menu,
                is_left_menu:item.is_left_menu,
                path:item.path+"/"+role_permissions[i].route,
                name:role_permissions[i].permission_name,
                authority:role_permissions[i].roles,
              }
            ]
          }

        }
      }
    })
  }
  return routes;
}
export function arrayBufferToBase64(buffer) {
  let binary = '';
  let bytes = new Uint8Array(buffer);
  let len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

export function formatData(data, result, type) {
  data.map(v => {
    let obj = {};
    obj.children = []
    obj.area_name = v.area_name;
    obj.area_id = v.area_id;
    obj.column1 = '0/0';
    obj.column2 = '0/0';
    obj.column3 = '0/0';
    obj.column4 = '0/0';
    obj.column5 = '0/0';
    if (v.children_area) {
      formatData(v.children_area, obj.children)
    }
    v.scene_list.map(k => {
      if (type == 'warning') {
        if (k.scene_name == '井盖位移') {
          obj.column1 = `${k.warning_history_created_total}/${k.warning_history_total}`
        } else if (k.scene_name == '井室液位') {
          obj.column2 = `${k.warning_history_created_total}/${k.warning_history_total}`
        } else if (k.scene_name == '路面积水') {
          obj.column4 = `${k.warning_history_created_total}/${k.warning_history_total}`
        } else if (k.scene_name == '有毒有害') {
          obj.column3 = `${k.warning_history_created_total}/${k.warning_history_total}`
        } else if (k.scene_name == '水质检测') {
          obj.column5 = `${k.warning_history_created_total}/${k.warning_history_total}`
        }
      } else if (type == 'device') {
        if (k.scene_name == '井盖位移') {
          obj.column1 = `${k.history_created_fail_quant - k.history_closed_fail_quant}/${k.device_history_total}`
        } else if (k.scene_name == '井室液位') {
          obj.column2 = `${k.history_created_fail_quant - k.history_closed_fail_quant}/${k.device_history_total}`
        } else if (k.scene_name == '路面积水') {
          obj.column4 = `${k.history_created_fail_quant - k.history_closed_fail_quant}/${k.device_history_total}`
        } else if (k.scene_name == '有毒有害') {
          obj.column3 = `${k.history_created_fail_quant - k.history_closed_fail_quant}/${k.device_history_total}`
        } else if (k.scene_name == '水质检测') {
          obj.column5 = `${k.history_created_fail_quant - k.history_closed_fail_quant}/${k.device_total}`
        }
      }
    })
    result.push(obj)
  })
  return result;
}



// 张宇 add 2020 02 24


export function queryPermissions() { //权限信息

  let p = []

  const info = JSON.parse(window.sessionStorage.getItem("userPermissions"))
  if (info) {
    p = info
  }

  return p
}
